﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace JXT.PrimaryKey.Batman.Web.Mvc.Results
{
    public class JsonpResult : JsonResult
    {
        public string Callback { get; private set; }

        public JsonpResult(string callback)
        {
            Callback = callback;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            //base.ExecuteResult(context);
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            HttpResponseBase response = context.HttpContext.Response;
            //response.AddHeader("P3P", "CP=\"CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA div COM NAV OTC NOI DSP COR\"");
            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string result = String.Format("{0}({1})", Callback, serializer.Serialize(Data));
                response.Write(result);
            }
        }
    }
}
